import React from 'react';
import { DatePicker } from 'antd';
import moment from 'moment';

const { RangePicker } = DatePicker;

export interface DateProps {
  type: 'single' | 'range';
  bizType?: string,
  defaultValue: any;
  disabled: boolean;
  value: any;
  allowClear?: boolean;
  picker: 'month' | 'year' | 'date';
  editable: boolean;
  onChange: (val: any) => void;
  style?: React.CSSProperties;
  showTime?: any | boolean;
  [propsName: string]: any;
}

const Date: React.FC<DateProps> = (props) => {
  // const field = useField();
  // const editable = field.editable;
  const { type = 'single', onChange, showTime, value, picker = 'date', style, bizType, afterTody, editable, ...xProps } = props;
  const handleDateChange = (date: any, dateString: any) => {
    let changeDate = dateString;
    if (type === 'range') {
      changeDate = dateString.filter((val: string) => val);
      changeDate = changeDate.length ? changeDate : undefined;
    }

    onChange?.(changeDate);
  };
  const handleValueFormat = () => {
    try {
      if (bizType) {
        const today = moment().format('YYYY-MM-DD');
        if (!value) handleDateChange(moment(), today)
        return moment()
      }
      if (!value) return value;
      if (type === 'range') {
        return value?.map((dt: any) => moment(dt));
      }
      if (type === 'single') {
        return moment(value);
      }
      return undefined;
    } catch (err) {
      console.error(
        `日期组件，type=single，value为string, type=range,value为[string,string],当前type=${type},value=${value}`,
      );
    }
  };
  const commonProps: any = {
    picker,
    value: handleValueFormat(),
    onChange: handleDateChange,
    showTime: showTime || false,
    ...xProps,
  };
  // 处理不可编辑日期
  const disabledDate = (current: any) => {
    // Can not select days before today and today
    return current && current < moment().endOf('day');
  }
  if (afterTody) {
    commonProps.disabledDate = disabledDate;
  }
  if (!editable) {
    return value || '';
  }
  return type === 'single' ? (
    <DatePicker
      className="ey-picker"
      style={{
        width: '100%',
        ...style,
      }}
      {...commonProps}
    />
  ) : (
    <RangePicker
      className="ey-picker"
      style={{
        width: '100%',
        ...style,
      }}
      {...commonProps}
    />
  );
};

export default Date;
